package com.evan.review.ipc;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.evan.review.R;

/**
 * Messenger通信示例
 * 演示如何使用Messenger实现跨进程通信
 */
public class MessengerDemoActivity extends AppCompatActivity {

    // 消息类型定义
    public static final int MSG_REGISTER_CLIENT = 1;
    public static final int MSG_UNREGISTER_CLIENT = 2;
    public static final int MSG_SET_VALUE = 3;
    public static final int MSG_GET_VALUE = 4;
    public static final int MSG_VALUE_CHANGED = 5;

    private EditText etMessage;
    private TextView tvReceivedMessage;
    private TextView tvServiceStatus;
    private Button btnSend, btnBind, btnUnbind;

    // 服务的Messenger
    private Messenger messengerService;
    // 标记是否已绑定服务
    private boolean isBound = false;

    // 用于接收服务端消息的Messenger
    private final Messenger incomingMessenger = new Messenger(new IncomingHandler());

    // 处理从服务接收到的消息
    private class IncomingHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case MSG_VALUE_CHANGED:
                    // 处理从服务接收到的消息
                    String receivedMessage = msg.getData().getString("data");
                    updateReceivedMessage(receivedMessage);
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    // 服务连接回调
    private final ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            // 获取服务的Messenger
            messengerService = new Messenger(service);
            isBound = true;
            updateServiceStatus(true);

            // 向服务发送注册消息
            registerToService();

            Toast.makeText(MessengerDemoActivity.this, "服务已连接", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // 服务异常断开连接
            messengerService = null;
            isBound = false;
            updateServiceStatus(false);
            Toast.makeText(MessengerDemoActivity.this, "服务已断开", Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_messenger_demo);

        // 初始化视图
        initViews();
        // 设置监听
        setupListeners();
    }

    private void initViews() {
        etMessage = findViewById(R.id.et_message);
        tvReceivedMessage = findViewById(R.id.tv_received_message);
        tvServiceStatus = findViewById(R.id.tv_service_status);
        btnSend = findViewById(R.id.btn_send);
        btnBind = findViewById(R.id.btn_bind);
        btnUnbind = findViewById(R.id.btn_unbind);

        updateServiceStatus(false);
    }

    private void setupListeners() {
        // 绑定服务
        btnBind.setOnClickListener(v -> bindMessengerService());

        // 解绑服务
        btnUnbind.setOnClickListener(v -> unbindMessengerService());

        // 发送消息
        btnSend.setOnClickListener(v -> {
            String message = etMessage.getText().toString().trim();
            if (!message.isEmpty()) {
                sendMessageToService(message);
            } else {
                Toast.makeText(this, "请输入要发送的消息", Toast.LENGTH_SHORT).show();
            }
        });

        // Messenger介绍
        findViewById(R.id.btn_messenger_intro).setOnClickListener(v -> showMessengerIntroduction());
    }

    // 绑定Messenger服务
    private void bindMessengerService() {
        Intent intent = new Intent(this, MessengerService.class);
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    // 解绑Messenger服务
    private void unbindMessengerService() {
        if (isBound) {
            // 向服务发送注销消息
            unregisterFromService();
            
            // 解绑服务
            unbindService(serviceConnection);
            messengerService = null;
            isBound = false;
            updateServiceStatus(false);
        }
    }

    // 注册到服务
    private void registerToService() {
        if (isBound && messengerService != null) {
            try {
                Message msg = Message.obtain(null, MSG_REGISTER_CLIENT);
                msg.replyTo = incomingMessenger;
                messengerService.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
                Toast.makeText(this, "注册客户端失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 从服务注销
    private void unregisterFromService() {
        if (isBound && messengerService != null) {
            try {
                Message msg = Message.obtain(null, MSG_UNREGISTER_CLIENT);
                msg.replyTo = incomingMessenger;
                messengerService.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    // 向服务发送消息
    private void sendMessageToService(String messageText) {
        if (isBound && messengerService != null) {
            try {
                // 创建消息对象
                Message msg = Message.obtain(null, MSG_SET_VALUE);
                
                // 将消息内容放入Bundle
                Bundle data = new Bundle();
                data.putString("data", messageText);
                msg.setData(data);
                
                // 设置回复目标
                msg.replyTo = incomingMessenger;
                
                // 发送消息
                messengerService.send(msg);
                
                Toast.makeText(this, "消息已发送", Toast.LENGTH_SHORT).show();
            } catch (RemoteException e) {
                e.printStackTrace();
                Toast.makeText(this, "发送消息失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "服务未连接，无法发送消息", Toast.LENGTH_SHORT).show();
        }
    }

    // 更新收到的消息显示
    private void updateReceivedMessage(String message) {
        if (message != null) {
            tvReceivedMessage.setText("收到服务回复: " + message);
        }
    }

    // 更新服务状态显示
    private void updateServiceStatus(boolean connected) {
        tvServiceStatus.setText("服务状态: " + (connected ? "已连接" : "未连接"));
        
        // 更新按钮状态
        btnBind.setEnabled(!connected);
        btnUnbind.setEnabled(connected);
        btnSend.setEnabled(connected);
    }

    // 显示Messenger介绍对话框
    private void showMessengerIntroduction() {
        new androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle("Messenger通信介绍")
                .setMessage("Messenger是Android提供的一种轻量级IPC机制，基于Handler和Binder实现。\n\n" +
                        "使用步骤：\n" +
                        "1. 服务端创建Handler和Messenger\n" +
                        "2. 重写Handler的handleMessage()处理客户端消息\n" +
                        "3. 服务返回Messenger的Binder给客户端\n" +
                        "4. 客户端使用服务的Messenger发送Message\n" +
                        "5. 客户端可创建自己的Messenger接收服务回复\n\n" +
                        "适用场景：\n" +
                        "- 简单的跨进程通信\n" +
                        "- 无需复杂的接口定义\n" +
                        "- 单向或简单双向数据传递\n\n" +
                        "注意：\n" +
                        "- Messenger是串行处理消息的，不支持并发\n" +
                        "- 只能传递Bundle支持的数据类型")
                .setPositiveButton("了解", null)
                .show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 确保在Activity销毁时解绑服务
        unbindMessengerService();
    }
} 